<?php

namespace app\api\controller;

use app\common\libs\ImeiLib;
use app\common\model\Model;
use app\common\model\Product;
use app\common\model\ProductType;

class ProductController extends BaseApiController
{

    public array $notNeedLogin = ['items', 'spec', 'info'];

    public function items()
    {
        $items = ProductType::select()->toArray();

        return $this->success('ok', $items);
    }

    public function itemsBySpec()
    {
        $modelId = $this->request->param('model_id');
        $product = Product::where('model_id', $modelId)->select();
        return $this->success('ok', $product->toArray());
    }




    public function spec()
    {
        $data = $tabList = [
            [
                'id'   => 1,
                'name' => '手机',
                'type' => 'phone',

                'children' => []
            ],

            [
                'id'       => 3,
                'name'     => '平板',
                'type'     => 'pad',
                'children' => []
            ],
        ];

        $items = Model::field('id,brand,img,type')->select()->toArray();
        $data2 = [];

        foreach ($items as $item) {
            $data2[$item['type']][] = [
                'id'       => $item['id'],
                'name'     => $item['brand'],
                'img'      => $item['img'],
                'type'     => $item['type'],
                'children' => []
            ];
        }


        return $this->success('ok', ['tabList' => $tabList, 'categoryList' => $data2]);
    }


    public function info()
    {
        $productTypeId = $this->request->param('product_type_id');
        $model_id = $this->request->param('model_id');
        $product = Product::where('model_id', $model_id)->with(['modelinfo'])->where('product_type_id', $productTypeId)->find();
        if (!$product) {
            return $this->fail('未找到该产品');
        }
        return $this->success('ok', $product->toArray());
    }


    public function getSpecByImei()
    {
        $imei = $this->request->param('imei');
        if (!$imei) {
            return $this->fail('请输入IMEI码');
        }
        $brand = $this->request->param('brand');
        if (!$brand) {
            return $this->fail('请输入品牌');
        }
        try {
            $res = ImeiLib::search($imei, ImeiLib::brand2Func($brand));
        }catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }

        $res['model_id'] = Model::where('brand', $res['brand'])->where('spec',$res['spec'])->value('id');
        if (!$res['model_id']) {
            return $this->fail('该机型'.$res['spec'].'未配置相关服务');
        }


        return $this->success('ok', $res);
    }

}